using System;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using MediaPortal.GUI.Video;
//using MediaPortal.Video.Database;
using MediaPortal.Util;
using MediaPortal.Dialogs;
using MediaPortal.Player;
using System.Data;
using System.ComponentModel;
using c3o.Framework.Web;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;
using System.IO;


namespace MediaPortal.GUI.Rss
{
	public class GUIuTorrent :  GUIDataTable, ISetupForm
	{

        [SkinControlAttribute(300)]   protected GUIButtonControl bttnRefresh = null;


        private System.Windows.Forms.Timer RefreshTimer;

        public override int GetID
        {
            get
            {
                return 61903;
            }
            set
            {
            }
        }

        private string WebUiUrl = "http://140.188.204.53:8080/gui/";
        private string WebUiLogin = "admin";
        private string WebUiPassword = "admin";



        protected override void OnShowContextMenu()
        {
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);

            if (dlg == null)
                return;

            dlg.Reset();
            dlg.SetHeading(924);                // Menu
            //			dlg.AddLocalizedString(335);		// Start
            //			dlg.AddLocalizedString(1032);		// Stop
            dlg.Add("Start");
            dlg.Add("Stop");
            //dlg.Add("Move Up");
            //dlg.Add("Move Down");
            dlg.Add("Remove");

            dlg.DoModal(GetID);

            switch (dlg.SelectedLabel)
            {
                case 0:       // Start
                    {
                        this.uTorentAction("Start");
                        break;
                    }

                case 1:      // Stop
                    {                        
                        this.uTorentAction("Stop");
                        break;
                    }

                //case 2:      // Move Up
                //    {
                //        this.uTorentAction("Up");
                //        break;
                //    }
                //case 3:      // Move Down
                //    {
                //        this.uTorentAction("Down");
                //        break;
                //    }
                case 2:      // Remove
                    {
                        this.uTorentAction("Remove");
                        break;
                    }
            }
        }


		protected override void OnPageLoad()
		{
			GUIPropertyManager.SetProperty("#header.label", "My uTorrent");

			base.OnPageLoad();

            this.ShowDownloads();
		}


        /// <summary>
        /// Stop timer when you leave the plugin
        /// </summary>
        /// <param name="newWindowId"></param>
        protected override void OnPageDestroy(int newWindowId)
        {
            this.RefreshTimer.Stop();
        }


        protected override void  LoadSettings()
        {
 	        base.LoadSettings();

            MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings("MediaPortal.xml");

            this.WebUiUrl = xmlreader.GetValue("torrents", "uTorrent.url");
            this.WebUiLogin = xmlreader.GetValue("torrents", "uTorrent.Login");
            this.WebUiPassword = xmlreader.GetValue("torrents", "uTorrent.Password");
            string interval = xmlreader.GetValue("torrents", "uTorrent.seconds");

            int seconds = 10;

            if (interval != null && interval.Length > 0)
            {
                seconds = int.Parse(interval);
            }

            this.RefreshTimer = new System.Windows.Forms.Timer();
            this.RefreshTimer.Interval = seconds * 1000;
            this.RefreshTimer.Tick += new EventHandler(this.ShowDownloads);
            this.RefreshTimer.Start();
        }


        /// <summary>
        /// Used by Timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowDownloads(object sender, System.EventArgs e)
        {
            this.ShowDownloads();
        }


        /// <summary>
        /// Show current downloads
        /// </summary>
        public void ShowDownloads()
        {
            DataTable uTdt = uTorrentData.TorrentList(WebUiUrl, WebUiLogin, WebUiPassword);

            if (uTdt != null)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Label");
                dt.Columns.Add("Path");
                dt.Columns.Add("Label2");
                dt.Columns.Add("DVDLabel");
                dt.Columns.Add("IconImage");

                //String.Format("{0:P2}", ((double)dl.DownloadStats.Uploaded / dl.TorrentInformation.Size));
                //item.Label2 = dl.DownloadStats.Status + " ( " + DownLoadPercent + " / " + UploadPercent + ") ";

                foreach (DataRow uTrow in uTdt.Rows)
                {
                    string lKey = uTrow["key"].ToString();
                    string status = uTrow["status"].ToString();
                    string lFileName = uTrow["FileName"].ToString();
                    string lPercentage = uTrow["percentage"].ToString();
                    string lBytes = uTrow["bytes"].ToString();
                    string lRatio = uTrow["ratio"].ToString();	// 24 = 0.024
                    string lPeers = uTrow["peers"].ToString();
                    string lPeers2 = uTrow["peers2"].ToString();
                    string lSeeds = uTrow["seeds"].ToString();
                    string lSeeds2 = uTrow["seeds2"].ToString();
                    string lSize = uTrow["Size"].ToString();
                    string lUpSpeed = uTrow["UpSpeed"].ToString();
                    string lDownSpeed = uTrow["DownSpeed"].ToString();
					string ETA = uTrow["ETA"].ToString();

					if (ETA.Length > 0) ETA = SecondsToDaysHoursMinutes(int.Parse(ETA));
                    if (lRatio.Length > 0) lRatio = String.Format("{0:N2}", Double.Parse(lRatio) / 1000);	// 24 = 0.024                
                    if (lSize.Length > 0) lSize = GUIHelper.FormatSize(ulong.Parse(lSize), 1);
                    if (lUpSpeed.Length > 0) lUpSpeed = GUIHelper.FormatSize(ulong.Parse(lUpSpeed), 1);
                    if (lDownSpeed.Length > 0) lDownSpeed = GUIHelper.FormatSize(ulong.Parse(lDownSpeed), 1);

                    string DownLoadPercent = String.Format("{0:P2}", Double.Parse(lPercentage) / 1000);
                    string UploadPercent = "0%";

                    string IconImage = "utInactive.png";

                    switch (status)
                    {
                        case "136":
                            IconImage = "utInactive.png";
                            status = "Stopped";
                            break;
                        case "233":
                            IconImage = "utInactive.png";
                            status = "Paused";
                            break;
                        case "137":
                            IconImage = "utSeeding.png";
                            status = "Seeding(F)";
                            break;
                        case "200":
                        case "201":
                            if (lPercentage == "1000")
                            {
                                status = "Seeding";
                                IconImage = "utSeeding.png";
                            }
                            else
                            {
                                status = "Downloading";
                                IconImage = "utDownloading.png";
                            }
                            break;
                    }

					string DVDLabel = lFileName + "\n" + status + "\nSize: " + lSize + "\nRatio: " + lRatio + "\nSeeds: " + lSeeds + " (" + lSeeds2 + ")\nPeers: " + lPeers + " (" + lPeers2 + ")" + "\nDown Speed: " + lDownSpeed + "\nUp Speed: " + lUpSpeed + "\nETA: " + ETA;


                    dt.Rows.Add(lFileName, lKey, status + " (" + DownLoadPercent + ")", DVDLabel, IconImage);
                }

                this.Datasource = dt;
                this.Databind();
                this.Refresh();
            }
            else
            {
                    // Stop Timer
                    this.RefreshTimer.Stop();

                    // Show Error message
                    GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                    pDlgOK.SetHeading("uTorrent " + GUILocalizeStrings.Get(257));//Error
                    pDlgOK.SetLine(1, this.WebUiUrl);
                    pDlgOK.DoModal(GUIWindowManager.ActiveWindow);
            }
        }



		public string SecondsToDaysHoursMinutes(int time)
		{
			int days = time / 86400;
			int hours = (time / 3600) - (days * 24);
			int minutes = (time / 60) - (days * 1440) - (hours * 60);
			int seconds = time % 60;    // Modulous

			if (days > 0) return String.Format("{3}d {2}h {1}m {0}s", seconds, minutes, hours, days);
			if (hours > 0) return String.Format("{2}h {1}m {0}s", seconds, minutes, hours);
			if (minutes > 0) return String.Format("{1}m {0}s", seconds, minutes);
			if (seconds > 0) return String.Format("{0}s", seconds);

			return "";
		}


		public override bool Init()
		{
			//this.RssFileName = "MyPodCasts.Feeds.opml.xml";
			//this.OpmlFileName = "MyPodCasts.Search.opml.xml";

			//g_Player.PlayBackStopped += new MediaPortal.Player.g_Player.StoppedHandler(OnPlayBackStopped);
			//g_Player.PlayBackEnded += new MediaPortal.Player.g_Player.EndedHandler(OnPlayBackEnded);
			//g_Player.PlayBackStarted += new MediaPortal.Player.g_Player.StartedHandler(OnPlayBackStarted);
	
			//return Load(GUIGraphicsContext.Skin + @"\MyPodCasts.xml");
            return Load(GUIGraphicsContext.Skin + @"\MyuTorrent.xml");
		}





		#region ISetupForm Members

		// Returns the name of the plugin which is shown in the plugin menu
		public string PluginName()
		{
			return "My uTorrent";
		}



		// Returns the description of the plugin is shown in the plugin menu
		public string Description()
		{
            return "My uTorrent";
		}



		// Returns the author of the plugin which is shown in the plugin menu
		public string Author()
		{
			return "fcsobel";
		}



		// show the setup dialog
		public void ShowPlugin()
		{
            Form setup = new uTorrentSetupForm();            
			setup.ShowDialog();
		}



		// Indicates whether plugin can be enabled/disabled
		public bool CanEnable()
		{
			return true;
		}

		// get ID of windowplugin belonging to this setup
		public int GetWindowId()
		{
			return this.GetID;
		}

		// Indicates if plugin is enabled by default;
		public bool DefaultEnabled()
		{
			return true;
		}

		// indicates if a plugin has its own setup screen
		public bool HasSetup()
		{
			return true;
		}


		/// <summary>
		/// If the plugin should have its own button on the main menu of Media Portal then it
		/// should return true to this method, otherwise if it should not be on home
		/// it should return false
		/// </summary>
		/// <param name="strButtonText">text the button should have</param>
		/// <param name="strButtonImage">image for the button, or empty for default</param>
		/// <param name="strButtonImageFocus">image for the button, or empty for default</param>
		/// <param name="strPictureImage">subpicture for the button or empty for none</param>
		/// <returns>true  : plugin needs its own button on home
		///          false : plugin does not need its own button on home</returns>
		//public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage)
		//{

		//    strButtonText = "UKNova";
		//    strButtonImage = String.Empty;
		//    strButtonImageFocus = String.Empty;
		//    strPictureImage = String.Empty;
		//    return false;
		//}

		public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage)
		{
			strButtonText = PluginName();
			strButtonImage = String.Empty;
			strButtonImageFocus = String.Empty;
			strPictureImage = String.Empty;
			return true;
		}
		#endregion

        
        protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            base.OnClicked(controlId, control, actionType);

            if (control == this.bttnRefresh) this.ShowDownloads();
        }


    	public override void OnAction(Action action)
		{
			base.OnAction(action);


            if (action.IsUserAction())
            {
                this.Refresh();
            }
		}


        protected void Refresh()
        {
            GUIListItem item = this.facadeView.SelectedListItem;
            if (item != null)
            {
                this.detailbox.Label = item.DVDLabel;
            }
        }

        protected override void OnStop()
        {
            this.uTorentAction("Stop");
        }

        protected override void OnPlay()
        {
            this.uTorentAction("Start");
        }


        private void uTorentAction(string Action)
        {
            GUIListItem item = this.facadeView.SelectedListItem;

            if (item != null)
            {
                string dl = item.Path as string;
                if (dl != null)
                {
                    switch (Action)
                    {
                        case "Remove":
                            GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_YES_NO);
                            if (null == dlgYesNo) return;
                            dlgYesNo.SetHeading(GUILocalizeStrings.Get(433));//delete watched recordings?
                            dlgYesNo.SetLine(1, item.Label);
                            //							dlgYesNo.SetLine(2, String.Empty);
                            //							dlgYesNo.SetLine(3, String.Empty);
                            dlgYesNo.SetDefaultToYes(true);
                            dlgYesNo.DoModal(GetID);

                            if (dlgYesNo.IsConfirmed)
                            {
                                uTorrentData.RemoveDownload(WebUiUrl, WebUiLogin, WebUiPassword, dl);
                            }                            
                            break;
                        case "Toggle":
                            //if (dl.DownloadStats.Status == "Stopped")
                            //{
                            //    uTorrentData.StartDownload(dl);
                            //}
                            //else
                            //{
                            //    uTorrentData.StopDownload(dl);
                            //}
                            break;
                        case "Start":
                            uTorrentData.StartDownload(WebUiUrl, WebUiLogin, WebUiPassword, dl);
                            break;
                        case "Stop":
                            if (item.IconImage == "utInactive.png")
                            {
                                this.uTorentAction("Remove");
                            }
                            else
                            {
                                uTorrentData.StopDownload(WebUiUrl, WebUiLogin, WebUiPassword, dl);
                            }
                            break;
                        //case "Up":
                        //    uTorrentData.MoveDownloadUp(dl);
                        //    break;
                        //case "Down":
                        //    uTorrentData.MoveDownloadDown(dl);
                        //    break;
                    }

                    this.ShowDownloads();
                }
            }
        }


	}
}